package com.shopcart.mobile;



import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyz.service.UserCouponService;
import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.domain.Code;
import com.demo.mobile.MobException;
import com.demo.mobile.MobileInfo;
import com.demo.util.DateUtil;
import com.demo.util.MathUtil;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.Order;
import com.shopcart.domain.OrderDetail;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreGoods;
import com.shopcart.service.OrderService;
import com.shopcart.service.QuickShoppingService;
import com.vsd.domain.UserCoupon;
import com.vsd.mobile.error.MEnumError;
import com.vsd.service.CodeService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StoreService;
import com.zy.order.proto.MSOrder.MCoupon;
import com.zy.order.proto.MSOrder.MCouponList;
import com.zy.order.proto.MSOrder.MDiscount;
import com.zy.order.proto.MSOrder.MGoodsCart;
import com.zy.order.proto.MSOrder.MGoodsCartList;
import com.zy.order.proto.MSOrder.MMiniGoodsList;
import com.zy.order.proto.MSOrder.MOrder;
import com.zy.order.proto.MSOrder.MOrderList;
import com.zy.order.proto.MSOrder.MQuickShopping;
import com.zy.sys.proto.MOCommon.MRet;
import com.zy.sys.proto.MOCommon.MRetEx;

@Controller
@RequestMapping("/mobile/")
public class MOrderController {
	
	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	StoreService storeService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	CodeService codeService;
	@Autowired
	OrderService orderService;
	@Autowired
	QuickShoppingService quickShoppingService;
	
	/**
	@api mGetCoupon mGetCoupon					//获取优惠券及匹配酒水优惠(需要登录)
	@param required string ids			//选购菜品商品id  逗号隔开
	@return MDiscount  
	*/
	@RequestMapping("/mGetCoupon")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MDiscount.Builder mGetCoupon(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto,String couponId) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		MDiscount.Builder ret = MDiscount.newBuilder();
		
		String storeId = "";
		BigDecimal total = BigDecimal.ZERO;
		BigDecimal totalWine = BigDecimal.ZERO;
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		for (MGoodsCart cart : requestProto.getListList()) {
			StoreGoods g = storeGoodsService.findById(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(StringUtils.isBlank(storeId)&&g.getType()!=2){
				storeId = g.getStoreId();
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}
		}
		
		Store store = storeService.findById(storeId);
		if(store==null) throw new MobException(MEnumError.STORE_NOT_FOUND);
		Integer wineRate = store.getWineRate();
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		ret.setInfo("满"+store.getWineBegin()+"元，送"+store.getWineBegin()*wineRate/1000+"元酒水");
		ret.setFull(store.getWineBegin()+"");
		ret.setDiscount(wineDis.toString());
		ret.setDisc(wineRate+"");
		//匹配优惠券
		MCoupon.Builder coupon = userCouponService.getBestCoupont(mobileInfo.getUserid(), storeId, total.add(winNeed),couponId);
		if(coupon!=null){
			ret.setCoupon(coupon);
			//总计
			BigDecimal t = total.add(winNeed).subtract(new BigDecimal(coupon.getValue()));
			if(t.compareTo(BigDecimal.ZERO)<0) t = BigDecimal.ZERO;
			ret.setTotal(t.toString());
		}else{
			//总计
			ret.setTotal(total.add(winNeed).toString());
		}
		return ret;
	}
	
	/**
	@api mCouponsByCart mCouponsByCart					//可用优惠券列表(需要登录)
	@param required MGoodsCartList cart			//购物篮
	@return MCouponList  
	*/
	@RequestMapping("/mCouponsByCart")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MCouponList.Builder mCouponsByCart(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		String storeId = "";
		BigDecimal total = BigDecimal.ZERO;
		BigDecimal totalWine = BigDecimal.ZERO;
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		for (MGoodsCart cart : requestProto.getListList()) {
			StoreGoods g = storeGoodsService.findById(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(StringUtils.isBlank(storeId)&&g.getType()!=2){
				storeId = g.getStoreId();
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}
		}
		
		Store store = storeService.findById(storeId);
		Integer wineRate = store.getWineRate();
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		//匹配优惠券
		return userCouponService.getUsableCouponList(mobileInfo.getUserid(), storeId, total.add(winNeed));
	}
	
	/**
	@api mGetTgCoupon mGetTgCoupon					//获取团购优惠券(需要登录)
	@param required MGoodsCartList cart			//购物篮
	@return MDiscount  
	*/
	@RequestMapping("/mGetTgCoupon")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MDiscount.Builder mGetTgCoupon(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto,String couponId) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		MDiscount.Builder ret = MDiscount.newBuilder();
		
		String storeId = "";
		BigDecimal total = BigDecimal.ZERO;
		for (MGoodsCart cart : requestProto.getListList()) {
			StoreGoods g = storeGoodsService.findById(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(g.getType()==1||g.getType()==3) throw new MobException(MEnumError.ONLY_TG_ALLOW);
			total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
		}
		
		//匹配优惠券
		MCoupon.Builder coupon = userCouponService.getBestCoupont(mobileInfo.getUserid(), storeId, total,couponId);
		if(coupon!=null){
			ret.setCoupon(coupon);
			//总计
			BigDecimal t = total.subtract(new BigDecimal(coupon.getValue()));
			if(t.compareTo(BigDecimal.ZERO)<0){
				t = BigDecimal.ZERO;
			}
			ret.setTotal(t.toString());
		}else{
			//总计
			ret.setTotal(total.toString());
		}
		
		return ret;
	}
	
	
	/**
	@api mPostDishOrder mPostDishOrder			//生成菜品订单
	@param required MGoodsCartList cart			//购物篮
	@return MRetEx //code 0 成功 title 订单价格 msg 订单号  
	*/
	@RequestMapping("/mPostDishOrder")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRetEx.Builder mPostDishOrder(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		return orderService.postSingleOrder(requestProto,mobileInfo.getUserid());
	}
	
	
	/**
	@api mPostTgOrder mPostTgOrder			//生成团购订单
	@param required MGoodsCartList cart			//购物篮
	@return MRetEx //code 0 成功 title 订单价格 msg 订单号  
	*/
	@RequestMapping("/mPostTgOrder")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRetEx.Builder mPostTgOrder(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		return orderService.postTgOrder(requestProto,mobileInfo.getUserid());
	}
	
	
	/**
	@api mToPay mToPay					//进入付款(需要登录)
	@param required number type			//1:支付宝 2:银联 3：微信
	@param required string id		//订单id
	 * @param cashId 现金券
	@return MRet //code 0 成功 msg 订单号 银联跟微信支付为tn号
	*/
	@RequestMapping("/mToPay")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mToPay(MobileInfo mobileInfo,Integer type,String id,String cashId) throws Exception {
		if(type==null) throw new MobException("type");
		if(StringUtils.isBlank(id)) throw new MobException("id");
		return  orderService.toPay(type, id, cashId, mobileInfo.getUserid());
	}
	
	 
	/**
	@api mOrderList mOrderList					//我的订单列表 分页
	@param required number state  //0全部
	@return MOrderList //
	*/
	@RequestMapping("/mOrderList")
	@MobileMethod(isPage=true)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MOrderList.Builder mOrderList(MobileInfo mobileInfo,Integer state,Integer page,Integer limit) throws Exception {
		if(state==null) state=0;
		return  orderService.selectMyOrderList(mobileInfo.getUserid(),state, page, limit);
	}
	
	 
	/**
	@api mOrderDetail mOrderDetail					//订单详情
	@param required string id			//订单id
	@return MOrder  
	*/
	@RequestMapping("/mOrderDetail")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MOrder.Builder mOrderDetail(MobileInfo mobileInfo , String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MOrder.Builder ret = MOrder.newBuilder();
		Order o = orderService.findById(id);
		if(o==null) throw new MobException(MEnumError.ORDER_NOT_FOUND);
		//查找orderDetail
		Collection<OrderDetail> list = orderService.selectDetails(id);
		int totalNum = 0 ;
		BigDecimal totalBefore = BigDecimal.ZERO;
		for (OrderDetail d : list) {
			MGoodsCart.Builder c = MGoodsCart.newBuilder();
			c.setName(d.getGoodsName());
			c.setNum(d.getNum());
			c.setType(d.getGoodsType());
			c.setImg(d.getGoodsImg());
			c.setPrice(MathUtil.bigToString(d.getNowPrice()));
			totalNum+=d.getNum();
			c.setId(d.getGoodsId());
			ret.addCarts(c);
			totalBefore = totalBefore.add(d.getNowPrice().multiply(new BigDecimal(d.getNum())));
		}
		
		ret.setCode(o.getCode());
		ret.setId(o.getId());
		if(o.getCashCoupon()!=null){
			ret.setCoupon(o.getCashCoupon().toString());
		}else{
			ret.setCoupon("0.00");
		}
		ret.setImg(ret.getCarts(0).getImg());
		ret.setInfo(o.getInfo());
		ret.setPayType(o.getPayType());
		if(!"1".equals(o.getBackState())){
			ret.setState(o.getBackState());
		}else{
			ret.setState(o.getState());
		}
		ret.setStoreId(o.getStoreId());
		ret.setStoreName(o.getStoreName());
		ret.setTime(DateUtil.dateAsOrder(o.getCreateTime()));
		ret.setTotal(totalNum);
		ret.setType(o.getType());
		if(o.getWineMoney()!=null){
			 ret.setWine(o.getWineMoney().toString());
		}else{
			 ret.setWine("0.00");
		}
		//能否评价
		if(o.getState()==4&&"0".equals(o.getHasComment())){//交易完成 且未评价
			ret.setCanComment(1);
		}else{
			ret.setCanComment(0);
		}
		ret.setTotalBefore(totalBefore.toString());
		ret.setTotalPrice(o.getTotalPay().toString());
		
		return  ret;
	}
	
	
	/**
	@api mFinishPay mFinishPay					//支付为0 调用接口
	@param required string id	//订单id
	@return MRet //code 0 可用 -1 不可用 msg 价格
	*/
	@SuppressWarnings("unused")
	@RequestMapping("/mFinishPay")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mFinishPay(MobileInfo mobileInfo,String id) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MRet.Builder ret = MRet.newBuilder();
		Order o = orderService.findById(id);
		if(o==null) throw new MobException(MEnumError.ORDER_NOT_FOUND);
		
		String out_trade_no = id;
		String trade_no = MathUtil.getFixLenthString(12);
		String trade_status = "SUCCESS";
		BigDecimal total = o.getTotalPay().add(o.getPriceChange());
		
		//调用支付回调
//		afterPay(out_trade_no, trade_no, trade_status, null, total);
		
		ret.setCode(0);	
		
		return  ret;
	}
	

	/**
	@api mUpdateOrder mUpdateOrder	//更新订单状态
	@param required string type	//type 操作类型 1:取消 2:申请退款 3:删除 
	@param required string id	//id 订单id
	@param optional string info	//info 退款原因
	@return MRet
	*/
	@RequestMapping("/mUpdateOrder")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mUpdateOrder(MobileInfo mobileInfo,String id,Integer type,String info) throws Exception {
		if(StringUtils.isBlank(id)) throw new MobException("id");
		MRet.Builder ret = MRet.newBuilder();
		Order order = orderService.findById(id);
		if(order==null) throw new MobException(MEnumError.ORDER_NOT_FOUND);
		
		Integer state = order.getState() == null ? 0 : order.getState();
		
		switch (type) {
			case 1 :
				/**********************************修改***取消订单**************************************************/
				if ((order.getPayType() == 1 && state != 1)||(order.getPayType() == 2 && state != 2)) {
					throw new MobException(MEnumError.ORDER_HASPAY_ERROR);
				}
				/**********************************修改***取消订单**************************************************/
				 
				// 退回优惠券
				String couponId = order.getStoreCoupon();
				if (StringUtils.isNotBlank(couponId)) {
					UserCoupon coupon = new UserCoupon();
					coupon.setId(couponId);
					coupon.setState(1);
					userCouponService.update(coupon);
				}
	
				order.setState(-1); // 取消订单
				order.setBackTime(new Date());
			/**********11271335*******************************/
				order.setBackReason(info);
			/************************************************/
				break;
			case 2 :
				order.setBackState(6); // 退款
				order.setBackTime(new Date());
			/*********11271335********************************/
				order.setBackReason(info);
			/************************************************/
				break;
			case 3 :
				// 删除已取消或已完成的订单
				if (order.getBackState() != 7){
					if (state == 1 || state == 3 || state == 2) {
						throw new MobException(MEnumError.ORDER_DELETE_ERROR);
					}
				}
				order.setIsShow(0);
				break;
			case 4 :
				if (state == 3){
					order.setState(4); // 交易完成
				}
				break;
			default :
				throw new MobException(MEnumError.PARAM_WRONG_ERROR);
		}
		order.setModifyTime(new Date());
		
		orderService.updateByPrimaryKey(order);
		
		ret.setCode(1);	
		
		return  ret;
	}
	
	
	 
	/**
	@api mQuickShopping mQuickShopping	//抢购信息
	@return MQuickShopping
	*/
	@SuppressWarnings("deprecation")
	@RequestMapping("/mQuickShopping")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MQuickShopping.Builder mQuickShopping(MobileInfo mobileInfo) throws Exception {
		MQuickShopping.Builder ret = MQuickShopping.newBuilder();
		
		List<String> periods = quickShoppingService.selectTodayPriod(mobileInfo.getAreaCode());
		if(periods.size()>0){
			Date now = new Date();
			Integer code = codeService.getQuickTime();//持续分钟数
			if(now.getHours() == Integer.parseInt(periods.get(0)) && now.getMinutes()>=code){
				periods.remove(0);
			}
			
			if(periods.size()>0){
				for (String str : periods) {
					ret.addTitle(str);
				}
				Date begin = DateUtil.strToDate(DateUtil.asShortString(now)+" "+periods.get(0)+":00:00", "yyyy-MM-dd HH:mm:ss");
				int sec = (int)(begin.getTime()/1000 - now.getTime()/1000);
				ret.setSeconds(sec);//最近一场还需秒数
				
				ret.setMinutes(code);
				 
//				List<String> list = quickShoppingService.selectGoodsImg(periods.get(0), mobileInfo.getAreaCode());
//				for (String img : list) {
//					ret.addImgs(StringUtil.emptyIfBlank(img));
//				}
			}
		}
		Code c = codeService.findOne("rebate@sys");
		if(c!=null) ret.addImgs(c.getValue());
		return ret;
	}
	
	
	
	/**
	@api MQuickGoodsList MQuickGoodsList	//抢购商品列表(分页)
	@param required string type	//场次
	@return MMiniGoodsList
	*/
	@RequestMapping("/mQuickGoodsList")
	@MobileMethod(isPage=true)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MMiniGoodsList.Builder mQuickGoodsList(MobileInfo mobileInfo,String type,Integer page,Integer limit) throws Exception {
		if (StringUtils.isBlank(type)) {throw new MobException("type");}
		return quickShoppingService.selectPeriodGoods(type, mobileInfo.getAreaCode());
	}
	
	/**
	@api mBeforePay mBeforePay					//进入付款前计算金额(需要登录)
	@param required string id		//订单id
	@return MRet //code 0 成功 msg 金额
	*/
	@RequestMapping("/mBeforePay")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder mBeforePay(MobileInfo mobileInfo,String id) throws Exception {
		if (StringUtils.isBlank(id)) {throw new MobException("id");}
		MRet.Builder ret = MRet.newBuilder();
		Order o = orderService.findById(id);
		if(o==null) throw new MobException(MEnumError.ORDER_NOT_FOUND);
 		BigDecimal total= o.getTotalPay();
 		//减去减免
 		total = total.add(o.getPriceChange());
 		ret.setCode(0);
 		ret.setMsg(MathUtil.bigToString(total));
		return ret;
	}
	 
}
